package com.example.myapplication

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import java.text.SimpleDateFormat
import java.util.*

class NotificationActivity : AppCompatActivity() {
    
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: NotificationAdapter
    private lateinit var buttonSendNotification: Button
    private lateinit var databaseHelper: DatabaseHelper
    private lateinit var swipeRefreshLayout: SwipeRefreshLayout
    private lateinit var editTextSearch: EditText
    private lateinit var buttonClearSearch: Button
    private lateinit var spinnerFilterType: Spinner
    private lateinit var buttonMarkAllRead: Button
    private lateinit var buttonDeleteAll: Button
    private lateinit var textUnreadCount: TextView
    private lateinit var layoutEmpty: LinearLayout
    
    private var allNotifications = listOf<Notification>()
    private var filteredNotifications = listOf<Notification>()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notification)
        
        databaseHelper = DatabaseHelper(this)
        
        initViews()
        setupListeners()
        loadNotifications()
    }
    
    private fun initViews() {
        recyclerView = findViewById(R.id.recyclerViewNotifications)
        recyclerView.layoutManager = LinearLayoutManager(this)
        
        adapter = NotificationAdapter(
            emptyList(),
            onItemClick = { notification ->
                showNotificationDetails(notification)
            },
            onMarkRead = { notification ->
                markNotificationAsRead(notification)
            }
        )
        recyclerView.adapter = adapter
        
        buttonSendNotification = findViewById(R.id.buttonSendNotification)
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout)
        editTextSearch = findViewById(R.id.editTextSearch)
        buttonClearSearch = findViewById(R.id.buttonClearSearch)
        spinnerFilterType = findViewById(R.id.spinnerFilterType)
        buttonMarkAllRead = findViewById(R.id.buttonMarkAllRead)
        buttonDeleteAll = findViewById(R.id.buttonDeleteAll)
        textUnreadCount = findViewById(R.id.textUnreadCount)
        layoutEmpty = findViewById(R.id.layoutEmpty)
        
        // 只有管理员可以发送通知
        val currentUser = UserSession.currentUser
        if (currentUser != null && 
            (currentUser.userType == UserType.SUPER_SUPER_ADMIN ||
             currentUser.userType == UserType.SUPER_ADMIN ||
             currentUser.userType == UserType.DEPARTMENT_ADMIN)) {
            buttonSendNotification.visibility = View.VISIBLE
        } else {
            buttonSendNotification.visibility = View.GONE
        }
        
        // 设置过滤器
        setupFilterSpinner()
    }
    
    private fun setupFilterSpinner() {
        val filterOptions = listOf("全部", "系统通知", "审批通知", "患者通知", "科室通知", "一般通知", "未读")
        val filterAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, filterOptions)
        filterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerFilterType.adapter = filterAdapter
    }
    
    private fun setupListeners() {
        buttonSendNotification.setOnClickListener {
            showSendNotificationDialog()
        }
        
        swipeRefreshLayout.setOnRefreshListener {
            loadNotifications()
        }
        
        editTextSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                filterNotifications()
                buttonClearSearch.visibility = if (s.isNullOrEmpty()) View.GONE else View.VISIBLE
            }
        })
        
        buttonClearSearch.setOnClickListener {
            editTextSearch.text.clear()
        }
        
        spinnerFilterType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                filterNotifications()
            }
            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        
        buttonMarkAllRead.setOnClickListener {
            showMarkAllReadDialog()
        }
        
        buttonDeleteAll.setOnClickListener {
            showDeleteAllDialog()
        }
    }
    
    private fun loadNotifications() {
        val currentUser = UserSession.currentUser
        if (currentUser == null) return
        
        allNotifications = databaseHelper.getNotificationsForUser(currentUser)
        filterNotifications()
        updateUnreadCount()
        swipeRefreshLayout.isRefreshing = false
    }
    
    private fun filterNotifications() {
        val searchText = editTextSearch.text.toString().trim()
        val filterType = spinnerFilterType.selectedItem.toString()
        
        filteredNotifications = allNotifications.filter { notification ->
            var matchesSearch = true
            var matchesFilter = true
            
            // 搜索过滤
            if (searchText.isNotEmpty()) {
                matchesSearch = notification.title.contains(searchText, ignoreCase = true) ||
                               notification.message.contains(searchText, ignoreCase = true)
            }
            
            // 类型过滤
            when (filterType) {
                "系统通知" -> matchesFilter = notification.type == NotificationType.SYSTEM
                "审批通知" -> matchesFilter = notification.type == NotificationType.APPROVAL
                "患者通知" -> matchesFilter = notification.type == NotificationType.PATIENT
                "科室通知" -> matchesFilter = notification.type == NotificationType.DEPARTMENT
                "一般通知" -> matchesFilter = notification.type == NotificationType.GENERAL
                "未读" -> matchesFilter = !notification.isRead
                else -> matchesFilter = true // "全部"
            }
            
            matchesSearch && matchesFilter
        }
        
        adapter.updateNotifications(filteredNotifications)
        updateEmptyState()
    }
    
    private fun updateEmptyState() {
        if (filteredNotifications.isEmpty()) {
            layoutEmpty.visibility = View.VISIBLE
            recyclerView.visibility = View.GONE
        } else {
            layoutEmpty.visibility = View.GONE
            recyclerView.visibility = View.VISIBLE
        }
    }
    
    private fun updateUnreadCount() {
        val unreadCount = allNotifications.count { !it.isRead }
        if (unreadCount > 0) {
            textUnreadCount.text = unreadCount.toString()
            textUnreadCount.visibility = View.VISIBLE
        } else {
            textUnreadCount.visibility = View.GONE
        }
    }
    
    private fun showSendNotificationDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_send_notification, null)
        val editTextTitle = dialogView.findViewById<EditText>(R.id.editTextTitle)
        val editTextMessage = dialogView.findViewById<EditText>(R.id.editTextMessage)
        val spinnerType = dialogView.findViewById<Spinner>(R.id.spinnerType)
        val spinnerTarget = dialogView.findViewById<Spinner>(R.id.spinnerTarget)
        
        // 设置通知类型
        val types = listOf("系统通知", "审批通知", "患者通知", "科室通知", "一般通知")
        val typeAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, types)
        typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerType.adapter = typeAdapter
        
        // 设置目标用户
        val targets = listOf("所有用户", "本科室用户", "指定用户")
        val targetAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, targets)
        targetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerTarget.adapter = targetAdapter
        
        AlertDialog.Builder(this)
            .setTitle("发送通知")
            .setView(dialogView)
            .setPositiveButton("发送") { _, _ ->
                val title = editTextTitle.text.toString().trim()
                val message = editTextMessage.text.toString().trim()
                val typeText = spinnerType.selectedItem.toString()
                val targetText = spinnerTarget.selectedItem.toString()
                
                if (title.isEmpty() || message.isEmpty()) {
                    Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }
                
                val type = when (typeText) {
                    "系统通知" -> NotificationType.SYSTEM
                    "审批通知" -> NotificationType.APPROVAL
                    "患者通知" -> NotificationType.PATIENT
                    "科室通知" -> NotificationType.DEPARTMENT
                    else -> NotificationType.GENERAL
                }
                
                val currentUser = UserSession.currentUser
                if (currentUser == null) return@setPositiveButton
                
                val notification = Notification(
                    title = title,
                    message = message,
                    type = type,
                    targetDepartment = if (targetText == "本科室用户") currentUser.department else "",
                    createdBy = currentUser.id
                )
                
                val result = databaseHelper.addNotification(notification)
                if (result > 0) {
                    Toast.makeText(this, "通知发送成功", Toast.LENGTH_SHORT).show()
                    loadNotifications()
                } else {
                    Toast.makeText(this, "发送失败", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun showNotificationDetails(notification: Notification) {
        val timeFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val details = """
            标题: ${notification.title}
            
            内容: ${notification.message}
            
            类型: ${when(notification.type) {
                NotificationType.SYSTEM -> "系统通知"
                NotificationType.APPROVAL -> "审批通知"
                NotificationType.PATIENT -> "患者通知"
                NotificationType.DEPARTMENT -> "科室通知"
                NotificationType.GENERAL -> "一般通知"
            }}
            
            时间: ${timeFormat.format(notification.createTime)}
            
            状态: ${if (notification.isRead) "已读" else "未读"}
        """.trimIndent()
        
        AlertDialog.Builder(this)
            .setTitle("通知详情")
            .setMessage(details)
            .setPositiveButton("确定") { _, _ ->
                if (!notification.isRead) {
                    markNotificationAsRead(notification)
                }
            }
            .show()
    }
    
    private fun markNotificationAsRead(notification: Notification) {
        val result = databaseHelper.markNotificationAsRead(notification.id)
        if (result) {
            loadNotifications()
        }
    }
    
    private fun showMarkAllReadDialog() {
        AlertDialog.Builder(this)
            .setTitle("标记全部已读")
            .setMessage("确定要将所有未读通知标记为已读吗？")
            .setPositiveButton("确定") { _, _ ->
                markAllNotificationsAsRead()
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun markAllNotificationsAsRead() {
        val unreadNotifications = allNotifications.filter { !it.isRead }
        var successCount = 0
        
        for (notification in unreadNotifications) {
            if (databaseHelper.markNotificationAsRead(notification.id)) {
                successCount++
            }
        }
        
        if (successCount > 0) {
            Toast.makeText(this, "已标记 $successCount 条通知为已读", Toast.LENGTH_SHORT).show()
            loadNotifications()
        } else {
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun showDeleteAllDialog() {
        AlertDialog.Builder(this)
            .setTitle("清空通知")
            .setMessage("确定要删除所有通知吗？此操作不可恢复。")
            .setPositiveButton("确定") { _, _ ->
                deleteAllNotifications()
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun deleteAllNotifications() {
        val currentUser = UserSession.currentUser
        if (currentUser == null) return
        
        val result = databaseHelper.deleteAllNotificationsForUser(currentUser)
        if (result > 0) {
            Toast.makeText(this, "已删除 $result 条通知", Toast.LENGTH_SHORT).show()
            loadNotifications()
        } else {
            Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show()
        }
    }
}

class NotificationAdapter(
    private var notifications: List<Notification>,
    private val onItemClick: (Notification) -> Unit,
    private val onMarkRead: (Notification) -> Unit
) : RecyclerView.Adapter<NotificationAdapter.NotificationViewHolder>() {

    class NotificationViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val textTitle: TextView = itemView.findViewById(R.id.textTitle)
        val textMessage: TextView = itemView.findViewById(R.id.textMessage)
        val textTime: TextView = itemView.findViewById(R.id.textTime)
        val textType: TextView = itemView.findViewById(R.id.textType)
        val buttonMarkRead: Button = itemView.findViewById(R.id.buttonMarkRead)
        val viewUnreadIndicator: View = itemView.findViewById(R.id.viewUnreadIndicator)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotificationViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_notification, parent, false)
        return NotificationViewHolder(view)
    }

    override fun onBindViewHolder(holder: NotificationViewHolder, position: Int) {
        val notification = notifications[position]
        val timeFormat = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
        
        holder.textTitle.text = notification.title
        holder.textMessage.text = notification.message
        holder.textTime.text = timeFormat.format(notification.createTime)
        
        val typeText = when(notification.type) {
            NotificationType.SYSTEM -> "系统"
            NotificationType.APPROVAL -> "审批"
            NotificationType.PATIENT -> "患者"
            NotificationType.DEPARTMENT -> "科室"
            NotificationType.GENERAL -> "一般"
        }
        holder.textType.text = typeText
        
        // 设置未读状态
        if (notification.isRead) {
            holder.buttonMarkRead.visibility = View.GONE
            holder.viewUnreadIndicator.visibility = View.GONE
            holder.itemView.alpha = 0.7f
        } else {
            holder.buttonMarkRead.visibility = View.VISIBLE
            holder.viewUnreadIndicator.visibility = View.VISIBLE
            holder.itemView.alpha = 1.0f
        }
        
        holder.itemView.setOnClickListener {
            onItemClick(notification)
        }
        
        holder.buttonMarkRead.setOnClickListener {
            onMarkRead(notification)
        }
    }

    override fun getItemCount(): Int = notifications.size

    fun updateNotifications(newNotifications: List<Notification>) {
        notifications = newNotifications
        notifyDataSetChanged()
    }
} 